package com.share.lagou.buffer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

/**
 * @author caifan
 * @since 2022/7/20
 */
public class ByteBufTest {
    public static void main(String[] args) {
        final ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(6, 10);
        printByteBufInfo("ByteBufAllocator.DEFAULT.buffer(3, 10)", buffer);
        buffer.writeBytes(new byte[]{1, 2});
        printByteBufInfo("write 2 bytes", buffer);
        // int 占用4字节
        buffer.writeInt(100);
        printByteBufInfo("buffer write int 100", buffer);
        buffer.writeBytes(new byte[]{3, 4, 5});
        printByteBufInfo("write 3 bytes", buffer);

        final byte[] read = new byte[buffer.readableBytes()];
        buffer.readBytes(read);
        printByteBufInfo("readBytes(" + buffer.readableBytes() + ")", buffer);
        printByteBufInfo("BeforeGetAndSet", buffer);
        // 内存地址 + 2位置的值
        System.out.println("getInt(2)==" + buffer.getInt(2));
        // 修改索引为1位置的值 writeIndex readIndex 不变
        buffer.setByte(1, 0);
        System.out.println("getByte(1)==" + buffer.getByte(1));
        printByteBufInfo("AfterGetAndSet", buffer);
    }

    private static void printByteBufInfo(String step, ByteBuf buffer) {
        System.out.println("--------" + step + "-------------");
        System.out.println("readerIndex:" + buffer.readerIndex());
        System.out.println("writerIndex:" + buffer.writerIndex());
        // 是否可读writeIndex > readIndex为true
        System.out.println("isReadable:" + buffer.isReadable());
        // capacity > writeIndex 为true
        System.out.println("isWritable:" + buffer.isWritable());
        System.out.println("readableBytes:" + buffer.readableBytes());
        System.out.println("writableBytes:" + buffer.writableBytes());
        System.out.println("maxWritableBytes:" + buffer.maxWritableBytes());
        System.out.println("capacity:" + buffer.capacity());
        System.out.println("maxCapacity:" + buffer.maxCapacity());
    }

}
